package com.atguigu.headline.controller;

import com.atguigu.headline.pojo.NewsHeadline;
import com.atguigu.headline.pojo.Result;
import com.atguigu.headline.pojo.ResultCodeEnum;
import com.atguigu.headline.service.NewsHeadlineService;
import com.atguigu.headline.service.impl.NewsHeadlineServiceImpl;
import com.atguigu.headline.util.JwtHelper;
import com.atguigu.headline.util.WebUtil;
import io.jsonwebtoken.Jwt;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.HashMap;

@WebServlet("/headline/*")
public class NewsHeadlineController extends BaseController {
    private NewsHeadlineService newsHeadlineService = new NewsHeadlineServiceImpl();


    protected void publish(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String token = req.getHeader("token");
        Long userId = JwtHelper.getUserId(token);
        int userid = userId.intValue();
        NewsHeadline newsHeadline = WebUtil.readJson(req, NewsHeadline.class);
        newsHeadline.setPublisher(userid);
        newsHeadlineService.insert(newsHeadline);
        WebUtil.writeJson(resp, Result.ok( null));
    }


    protected void findHeadlineByHid(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("hid");
        HashMap map=new HashMap();
        NewsHeadline newsHeadline= newsHeadlineService.query();
        map.put("headline",newsHeadline);
        WebUtil.writeJson(resp, Result.ok(map));
    }


    protected void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        NewsHeadline newsHeadline = WebUtil.readJson(req, NewsHeadline.class);;
        int cows=newsHeadlineService.update(newsHeadline);
        if(cows>0){
            WebUtil.writeJson(resp, Result.ok(null));
        }else{
            WebUtil.writeJson(resp, Result.build(null, ResultCodeEnum.NOTLOGIN));
        }
    }


    protected void removeByHid(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int hid = Integer.parseInt(req.getParameter("hid"));
        int cows=newsHeadlineService.delte(hid);
        if(cows>0){
            WebUtil.writeJson(resp, Result.ok(null));
        }else{
            WebUtil.writeJson(resp, Result.build(null, ResultCodeEnum.NOTLOGIN));
        }
    }
}